
var $connections_list;
$.connections_init = function()
{
	$connections_list = $('#connections').connections({
          select: function(e,ui){
           // alert(ui.value.key);
          }
    });
    
    $("#connections-button").click(function(){
        $connections_list.connections('list');
    	$('#connections-content').dialog({resizable:false,modal:true,width:795});
    });
    
    var auth_window_f = function(type){
      	window.open('/connections/authorize?type='+type+'&callback=$.connection_complete','','width=700,height=400');
    }
    $("#create-twitter-authorization-button").click(function(){ auth_window_f("Twitter");  });
    $("#create-google-analytics-authorization-button").click(function(){ auth_window_f("GoogleAnalytics"); });
    $("#create-vimeo-authorization-button").click(function(){ auth_window_f("Vimeo"); });
    $("#create-youtube-authorization-button").click(function(){ auth_window_f("YouTube");  });
    $("#create-facebook-authorization-button").click(function(){ auth_window_f("Facebook"); });
    		
}

$.connection_complete = function()
{
    $connections_list.connections('list');
}




/**
 *  connections
 */

$.widget( "impact.connections",
{

  _create: function()
  {
    var self = this, el = this.element;
    self._$clist = $(el).clist({
  	  addable: 			false,
      //add:              function(e,ui){ self._add() },
      deletef:          function(e,ui){ self._delete(ui.index); },
      select:           function(e,ui){ self._trigger('select',0,ui) },
      cell_renderer:    function(d){
      	var type = d.type;
      	if (d.type=="GoogleAnalytics")
      		type = "Google Analytics";
      	
    	var name = d.username;
    	if (d.type=="GoogleAnalytics")
    		name = name.substring(name.lastIndexOf(' '));
    	
    	if (d.type=="Twitter")
    		name = "@"+name;
    	  
    	var html = "<div class='item'>";
    	html += "<table cellpadding='0' cellspacing='0' border='0'><tr valign='top'>";
    	html += "<td width='23'>o</td>";//TODO indicate state of connection
    	html += "<td width='195'><b>"+type+"</b><br/>Connected</td>"; //TODO indicate state of connection
    	html += "<td width='195'><b>"+name+"</b><br/>";
    	var last_mod = 0;
        for (var i=0; i<d.children.length; i++)
        {
        	var n = d.children[i].widget.name;
        	if (d.children[i].modified>last_mod)
        		last_mod = d.children[i].modified;
        	var sel_vals = d.children[i].selector_display_values;
        	var args = "";
        	for(var p in sel_vals)
        	{
        		var v = sel_vals[p];
        		args += v+" ";
        	}
        	if (args.length!=0)
        	{
        		args = args.substring(0,args.length-1);
        		n = n + " ("+args+")";
        	}
        	html += n+"<br/>";
        }
        html += "</td>";
        
        if (last_mod==0) 
        	last_mod = d.modified;
        html += "<td width='150'>"+format_date_ago(last_mod)+"</td>";
        html += "<td width='150'>"+format_date(d.created)+"</td>";
        html += "</tr></table>";
        console.log(d);
        return $(html);
      },
      deletable:        true,
      selectable:       true
    })
  },

  list: function()
  {
    var self = this;
    $.get_json('/api/connections/list/all', null, function(evt_data)
    {
      self.value(evt_data);
    });
  },

  value: function(t)
  {
    var self = this;
    if (t==null)
      return self._$clist.clist('value');
    self._$clist.clist('value',t);
  },

  select: function(index)
  {
    var self = this, el = this.element;
    self._$clist.clist('select',index);
  },

  _add: function()
  {
    var self = this, el = this.element;
    $.dialog_input('Add a connection','Name','Ok','Cancel',
      function(name) {
        $.get_json('/api/connections/add/'+name, null, function(data) {
          // self._\$clist.clist('add_value',data);
          // var idx = self.value().length-1;
          // self.select(idx);
          // self._trigger('select',0,{index: idx});
          self.list();
        });
      });

  },

  _delete: function(idx)
  {
    var self = this, el = this.element;
    var value = self.value();
    var d = value[idx];
    $.dialog_ok('Really','Are you sure you want to delete the connection '+d.type+' '+d.username+'?','Ok','Cancel',
      function() {
        $.get_json('/api/connections/delete/'+value[idx].key, null, function(data) {
           self._$clist.clist('remove',idx);
           idx--;
           if (idx<0) idx=0;
           self.select(idx);
           self._trigger('select',0,{index: idx});
        });
      });
  }


});


/** date formatting utils **/
var format_date_ago = function(time){
	var date = new Date(time),
	diff = (((new Date()).getTime() - date.getTime()) / 1000),
	day_diff = Math.floor(diff / 86400);
		
	if ( isNaN(day_diff) || day_diff < 0 || day_diff >= 31 )
		return;
			
	return day_diff == 0 && (
			diff < 60 && "just now" ||
			diff < 120 && "1 minute ago" ||
			diff < 3600 && Math.floor( diff / 60 ) + " minutes ago" ||
			diff < 7200 && "1 hour ago" ||
			diff < 86400 && Math.floor( diff / 3600 ) + " hours ago") ||
		day_diff == 1 && "Yesterday" ||
		day_diff < 7 && day_diff + " days ago" ||
		day_diff < 31 && Math.ceil( day_diff / 7 ) + " weeks ago";
}
var format_date = function(time)
{
	var d = new Date(time);
	return d.getMonth()+"/"+d.getDate()+"/"+d.getFullYear();
}